/*
=====================================================================

  ColumnComparator.java
  
  Created by Claude Duguay
  Copyright (c) 2002
  
  Updated STL 04 DEC 2004 - compare uses ArrayList and not Vector anymore
  
=====================================================================
*/

package who.tmap.ui.util.jsorttable;

import java.util.*;

@SuppressWarnings("unchecked")
public class ColumnComparator implements Comparator {
  protected int index;
  protected boolean ascending;
  
  public ColumnComparator(int index, boolean ascending)
  {
    this.index = index;
    this.ascending = ascending;
  }
  
  @SuppressWarnings("unchecked")
  public int compare(Object one, Object two) 
  {
    if (one instanceof ArrayList &&
        two instanceof ArrayList)
    {
        ArrayList vOne = (ArrayList)one;
        ArrayList vTwo = (ArrayList)two;
      Object oOne = vOne.get(index);
      Object oTwo = vTwo.get(index);
      if (oOne instanceof Comparable &&
          oTwo instanceof Comparable)
      {
        Comparable cOne = (Comparable)oOne;
        Comparable cTwo = (Comparable)oTwo;

        if (ascending)
        {
          return cOne.compareTo(cTwo);
        }
        else
        {
          return cTwo.compareTo(cOne);
        }

        // STL 29 AUG 2007
        // Takes care of null values !
      } else {
    	  if ( oOne == null ) {
    		  if ( ascending ) {
    			  return -1;
    		  } else {
    			  return 1;
    		  }
    	  } else if ( oTwo == null ) {
    		  if ( ascending ) {
    			  return 1;
    		  } else {
    			  return -1;
    		  }
    	  }
      }
    }
    return 1;
  }
}

